package com.bigtotoro.shuiyincamera.image;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.editimage.Constacts;
import com.bigtotoro.shuiyincamera.adapter.ColorListAdapter;
import com.bigtotoro.shuiyincamera.editimage.task.StickerTask;
import com.bigtotoro.shuiyincamera.editimage.ui.ColorPicker;
import com.bigtotoro.shuiyincamera.editimage.utils.BitmapUtils;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.editimage.utils.Matrix3;
import com.bigtotoro.shuiyincamera.editimage.view.CustomPaintView;
import com.bigtotoro.shuiyincamera.editimage.view.PaintModeView;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouch;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouchBase;
import com.bigtotoro.shuiyincamera.util.FileUtils;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

import qiu.niorgai.StatusBarCompat;

/**
 * 画板,暂时只要涂鸦功能
 */
public class Palette02Activity extends BaseActivity implements View.OnClickListener, ColorListAdapter.IColorListAction {
    public static final int REQUEST_PERMISSON_SORAGE = 1;
    public static final int ACTION_REQUEST_EDITIMAGE = 9;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_palette02);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.font_0));

        //添加友盟事件统计
        MyUtils.addUmengEvent(Palette02Activity.this,"img_free_edit","图片自由编辑");

        initBase();
        initView();
        getData();
    }

    public TextView btn_submit;
    private View backBtn;
    private Palette02Activity context;
    public ImageViewTouch mainImage; // 底部图层，放原始照片这一层
    private Bitmap mainBitmap;
    private int imageWidth, imageHeight;
    public CustomPaintView mPaintView;//涂鸦模式画板

    private PaintModeView mPaintModeView;
    private RecyclerView mColorListView;//颜色列表View
    private ColorListAdapter mColorAdapter;
    private View popView;
    private ColorPicker mColorPicker;//颜色选择器
    private PopupWindow setStokenWidthWindow;
    private SeekBar mStokenWidthSeekBar;
    private ImageView mEraserView;
    public boolean isEraser = false;//是否是擦除模式
    private LinearLayout menu_layout;

    private SaveCustomPaintTask mSavePaintImageTask;

    public int[] mPaintColors = {Color.BLACK,
            Color.DKGRAY, Color.GRAY, Color.LTGRAY, Color.WHITE,
            Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN, Color.MAGENTA};

    private void initView() {
        btn_submit = findViewById(R.id.btn_submit);
        btn_submit.setOnClickListener(this);

        mainImage = findViewById(R.id.main_image);// 页面正中的图片显示控件
        mPaintView = findViewById(R.id.custom_paint_view);//涂鸦画布
        mPaintView.setVisibility(View.VISIBLE);

        backBtn = findViewById(R.id.back_btn);// 左上角退出按钮
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        menu_layout = findViewById(R.id.menu_layout);
        mPaintModeView = (PaintModeView)findViewById(R.id.paint_thumb);
        mColorListView = (RecyclerView)findViewById(R.id.paint_color_list);//颜色列表
        mEraserView = (ImageView) findViewById(R.id.paint_eraser);

        mColorPicker = new ColorPicker(this, 255, 0, 0);
        initColorListView();
        mPaintModeView.setOnClickListener(this);

        initStokeWidthPopWindow();
        mEraserView.setOnClickListener(this);
        updateEraserView();
    }

    private void updateEraserView() {
        mEraserView.setImageResource(isEraser ? R.drawable.eraser_seleced : R.drawable.eraser_normal);
        mPaintView.setEraser(isEraser);
    }
    private void initStokeWidthPopWindow() {
        popView = LayoutInflater.from(Palette02Activity.this).
                inflate(R.layout.view_set_stoke_width, null);
        setStokenWidthWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT
                , ViewGroup.LayoutParams.WRAP_CONTENT);

        mStokenWidthSeekBar = (SeekBar) popView.findViewById(R.id.stoke_width_seekbar);

        setStokenWidthWindow.setFocusable(true);
        setStokenWidthWindow.setOutsideTouchable(true);
        setStokenWidthWindow.setBackgroundDrawable(new BitmapDrawable());
        setStokenWidthWindow.setAnimationStyle(R.style.popwin_anim_style);

        mPaintModeView.setPaintStrokeColor(Color.RED);
        mPaintModeView.setPaintStrokeWidth(10);

        updatePaintView();
    }

    private void updatePaintView() {
        isEraser = false;
        updateEraserView();
        mPaintView.setColor(mPaintModeView.getStokenColor());
        mPaintView.setWidth(mPaintModeView.getStokenWidth());
    }
    /**
     * 初始化颜色列表
     */
    private void initColorListView() {
        mColorListView.setHasFixedSize(false);
        LinearLayoutManager stickerListLayoutManager = new LinearLayoutManager(Palette02Activity.this);
        stickerListLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mColorListView.setLayoutManager(stickerListLayoutManager);
        mColorAdapter = new ColorListAdapter(this, mPaintColors, this, mPaintView);
        mColorListView.setAdapter(mColorAdapter);
    }


    public static String filePath;// 需要编辑图片路径
    public String saveFilePath;// 生成的新图片路径
    private void getData() {
        context = this;
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels;
        imageHeight = metrics.heightPixels;

        filePath = getIntent().getStringExtra("path"); //图片原始路径
        File outputFile = FileUtils.genEditFile();  //保存路径
        saveFilePath = outputFile.getAbsolutePath();
        loadImage(filePath);
    }

    private LoadImageTask mLoadImageTask;
    public void loadImage(String filepath) {
        if (mLoadImageTask != null) {
            mLoadImageTask.cancel(true);
        }
        mLoadImageTask = new LoadImageTask();
        mLoadImageTask.execute(filepath);
    }

    @Override
    public void onColorSelected(int position, int color) {
        setPaintColor(color);
    }

    @Override
    public void onMoreSelected(int position) {
        mColorPicker.show();
        Button okColor = (Button) mColorPicker.findViewById(R.id.okColorButton);
        okColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setPaintColor(mColorPicker.getColor());
                mColorPicker.dismiss();
            }
        });
    }
    /**
     * 设置画笔粗细
     * show popwidnow to set paint width
     */
    protected void setStokeWidth() {
        if (popView.getMeasuredHeight() == 0) {
            popView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        }

        mStokenWidthSeekBar.setMax(mPaintModeView.getMeasuredHeight());

        mStokenWidthSeekBar.setProgress((int) mPaintModeView.getStokenWidth());

        mStokenWidthSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mPaintModeView.setPaintStrokeWidth(progress);
                updatePaintView();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        int[] locations = new int[2];
        menu_layout.getLocationOnScreen(locations);
        setStokenWidthWindow.showAtLocation(menu_layout,Gravity.NO_GRAVITY,
                0, locations[1] - popView.getMeasuredHeight());
    }
    /**
     * 设置画笔颜色
     *
     * @param paintColor
     */
    protected void setPaintColor(final int paintColor) {
        mPaintModeView.setPaintStrokeColor(paintColor);

        updatePaintView();
    }
    /**
     * 这个方法是为了获取图片的，异步获取图片方法
     */
    private final class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {
            return BitmapUtils.getSampledBitmap(params[0],
                    imageWidth / 4, imageHeight / 4);
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        @Override
        protected void onCancelled(Bitmap result) {
            super.onCancelled(result);
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected void onPostExecute(Bitmap result) {
            changeMainBitmap(result, false);
        }
    }
    private void toggleEraserView() {
        isEraser = !isEraser;
        updateEraserView();
    }

    /**
     * @param newBit
     * @param needPushUndoStack
     */
    public void changeMainBitmap(Bitmap newBit, boolean needPushUndoStack) { //第二个参数是是否将图片压栈
        if (newBit == null)  //如果获取到的图片为空，返回
            return;
        if (mainBitmap == null || mainBitmap != newBit) {  //如果获取到的图片为空，返回
            mainBitmap = newBit;
            mainImage.setImageBitmap(mainBitmap);
            mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSavePaintImageTask != null && !mSavePaintImageTask.isCancelled()) {
            mSavePaintImageTask.cancel(true);
        }
    }
    /**
     * 保存涂鸦
     */
    public void applyPaintImage() {
        if (mSavePaintImageTask != null && !mSavePaintImageTask.isCancelled()) {
            mSavePaintImageTask.cancel(true);
        }
        mSavePaintImageTask = new SaveCustomPaintTask(Palette02Activity.this);
        mSavePaintImageTask.execute(mainBitmap);
    }

    /**
     * 文字合成任务
     * 合成最终图片
     */
    private final class SaveCustomPaintTask extends StickerTask {

        public SaveCustomPaintTask(Activity activity) {
            super(activity);
        }

        @Override
        protected Bitmap doInBackground(Bitmap... bitmaps) {
            // System.out.println("保存贴图!");
            // 先把mainBitmap复制了一份到resultBit中
            //用canvas设置这个resultBit的bitmap作为背景画布，将文字绘制在上面
            Matrix touchMatrix = mainImage.getImageViewMatrix(); //touchMatrix是不变的
            Bitmap resultBit = Bitmap.createBitmap(bitmaps[0]).copy(
                    Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(resultBit);//画布是根据传入的bitmap生成的画布

            float[] data = new float[9];
            //将mainImage的矩阵数据复制到data数组中
            touchMatrix.getValues(data); // 底部图片变化记录矩阵原始数据
            Matrix3 cal = new Matrix3(data); // 辅助矩阵计算类
            Matrix3 inverseMatrix = cal.inverseMatrix(); // 计算逆矩阵
            Matrix m = new Matrix();
            m.setValues(inverseMatrix.getValues());

            int width = resultBit.getWidth();
            int height = resultBit.getHeight();

            /**两个方法分开执行，互不干扰**/
            handleImage2(canvas, m, width, height); //根据传入的bitmap生成的画布，根据mainImage计算出的矩阵
            handleImage(canvas, m); //根据传入的bitmap生成的画布，根据mainImage计算出的矩阵
            return resultBit;
        }

        @Override
        public void handleImage(Canvas canvas, Matrix m) {
            float[] f = new float[9];
            m.getValues(f);
            int dx = (int) f[Matrix.MTRANS_X];
            int dy = (int) f[Matrix.MTRANS_Y];
            float scale_x = f[Matrix.MSCALE_X];
            float scale_y = f[Matrix.MSCALE_Y];
            canvas.save();
            canvas.translate(dx, dy);
            canvas.scale(scale_x, scale_y);

            if (mPaintView.getPaintBit() != null) {
                canvas.drawBitmap(mPaintView.getPaintBit(), 0, 0, null);
            }
            canvas.restore();
        }

        @Override
        public void handleImage2(Canvas canvas, Matrix m, int width, int height) {

        }

        @Override
        public void onPostResult(Bitmap result) {
            mPaintView.reset();
            changeMainBitmap(result, true);
            backToMain();
            doSaveImage();
        }

    }//end inner class

    /**
     * 返回主菜单
     */
    public void backToMain() {
        mainImage.setVisibility(View.VISIBLE);
        mPaintView.setVisibility(View.GONE);//画布消失没有错，但是再次点击底部菜单时，应该让他再次显示
    }
    private  SaveImageTask mSaveImageTask;
    public  void doSaveImage() {
        if (mSaveImageTask != null) {
            mSaveImageTask.cancel(true);
        }
        //在这里保存bitmap_list里的内容，取后一半的数据
        mSaveImageTask = new SaveImageTask();
        mSaveImageTask.execute(mainBitmap); //保存的是mainBitmap

    }
    private  final class SaveImageTask extends AsyncTask<Bitmap, Void, Boolean> {
        private Dialog dialog;
        @Override
        protected Boolean doInBackground(Bitmap... params) {
            if (TextUtils.isEmpty(saveFilePath))  //saveFilePath通过EditImageActivity.start方法中传入的
                return false;
            return BitmapUtils.saveBitmap(params[0], saveFilePath);
        }
        @Override
        protected void onCancelled() {
            super.onCancelled();
            dialog.dismiss();
        }
        @Override
        protected void onCancelled(Boolean result) {
            super.onCancelled(result);
            dialog.dismiss();
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = BaseActivity.getLoadingDialog(Palette02Activity.this, R.string.saving_image,
                    false);
            dialog.show();
        }
        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            dialog.dismiss();
            if (result) {
                //放入图片列表
                MyArt art = new MyArt();
                art.setHeight(imageHeight);
                art.setWidth(imageWidth);
                Long millis = System.currentTimeMillis();
                art.setCreate_time(millis+"");
                art.setPath(saveFilePath);
                art.setType(0);
                art.save();
                Toast.makeText(context, "图片保存在" + saveFilePath.toString(),
                        Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(context, ShowMyArtsActivity.class);
                intent.putExtra(Constacts.EXTRA_OUTPUT, saveFilePath);
                intent.putExtra("create_time", art.getTrueCreateTime());
                intent.putExtra("width", imageHeight);
                intent.putExtra("height", imageWidth);
                intent.putExtra("type", "0");

                FileUtil.ablumUpdate(context, saveFilePath,0);//更新相册
                startActivity(intent);
                finish();
            } else {
                Toast.makeText(context, R.string.save_error, Toast.LENGTH_SHORT).show();
            }
        }
    }



    @Override
    public void onClick(View v) {
            if (v == mPaintModeView) {//设置绘制画笔粗细
                setStokeWidth();
            } else if (v == mEraserView) {
                toggleEraserView();
            } else if (v == btn_submit) { //应用/保存

                //添加友盟事件统计
                MyUtils.addUmengEvent(Palette02Activity.this,"img_free_edit_save","图片自由编辑保存");
                    applyPaintImage();

            }
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("Palette02Activity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("Palette02Activity");//统计页面
        MobclickAgent.onPause(this);
    }

}
